package model;

import java.util.Timer;

import controler.Helper;

public class SystemMonitor {
	private Boolean stop;
	private Sensor sensor;
	private Double aimValue;
	private Double windowValue;
	private Exception fail;
	private final Timer timer = new Timer("SystemMonitor");

	public void controlValue(Sensor sensor, Double aimValue, Double windowValue) throws Exception {
		start();
		fail = null;
		this.sensor = sensor;
		this.aimValue = aimValue;
		this.windowValue = windowValue;
		Monitor monitor = new Monitor();
		monitor.start();

	}

	public void checkState() throws Exception {
		if (fail != null) {
			throw fail;
		}
	}

	public void stop() {
		stop = Boolean.TRUE;
	}

	private void start() {
		stop = Boolean.FALSE;
	}

	private class Monitor extends Thread {

		@Override
		public void run() {
			Double value = sensor.getSensedValue().getValue();
			while (sensor.getSensedValue().isInRangeOf(aimValue, windowValue) && !stop) {
				Helper.miniPause();
				value = sensor.getSensedValue().getValue();
			}
			fail = new Exception("The " + sensor + " registered a value of " + value + " which is out of range.");
		}

	}
}
